<style type="text/css">
	img.upload-preview{
		margin:20px;
	}
	table#table-product .subtext{
		font-size:10pt;
		line-height:17px;
	}	
</style>
<div class="panel-manage">
	<div class="navbar navbar-inverse">
		<div class="navbar-inner">		
			<div class="flu-id">
				<div class="span6">
					<ul class="nav">        			
						<li class="dropdown">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown">หมวดหมู่ <b class="caret"></b></a>
							<ul class="dropdown-menu">
								<?php for ($i=0; $i<count($categories); $i++): ?>
									<?php if ($categories[$i]['CAF_PDT_CAT_ID'] == -1): ?>
										<li><a href="<?php print base_url() . $cafe_name; ?>/backend/product">
											<?php print $categories[$i]['CAF_PDT_CAT_NAME']; ?></a></li>
									<?php else:?>
										<li><a href="<?php print base_url() . $cafe_name; ?>/backend/product?c=<?php print $categories[$i]['CAF_PDT_CAT_ID']; ?>">
											<?php print $categories[$i]['CAF_PDT_CAT_NAME']; ?></a></li>
									<?php endif; ?>
								<?php endfor; ?>						
							</ul>
						</li>									
					</ul>	
				</div>
				<div class="span6 text-right">
					<button class="btn btn-primary" id="btn-product-add">เพิ่ม</button>					
					<button class="btn" id="btn-select-all" value="0"><i class="icon-ok"></i> เลือกทั้งหมด</button>					
	        		<button class="btn btn-danger" id="btn-product-remove-select">ลบที่เลือก</button>
				</div>			
			</div>                
		</div>
	</div>	
	<div class="panel-message"></div>
	<div class="alert alert-info" style="margin-top:10px;"><p><i class="icon-info-sign"></i>
		<small>ความกว้างและยาวที่เหมาะสมของ<b>รูปสินค้า</b> <?= $image_config['pdt_img_limit_width'] ?> x <?= $image_config['pdt_img_limit_height'] ?> พิกเซล และขนาดรูปภาพไม่เกิน 
			<?= ($image_config['pdt_img_limit_size'] / 1000); ?>kb สนับสนุนไฟล์รูปภาพ
			<?php print implode(',', array_unique(explode(',', strtolower(implode(',', array_unique($image_config['pdt_img_extensions'])))))); ?>
		</small></p>
	</div>
	<div>
		<table class="table table-striped table-hover" id="table-product">
			<tbody>
				<?php if (count($data) > 0):
						for ($i=0; $i<count($data); $i++): ?>
							<tr>
								<td><input type="checkbox" id="chk-p" name="chk-p" value="<?php print $data[$i]['CAF_PDT_CODE']; ?>" /></td>
								<td><img src="<?php print $data[$i]['CAF_PDT_IMG']; ?>" style="width:50px; height:50px;" /></td>
								<td>
									<span class="block"><b><?php print $data[$i]['CAF_PDT_NAME']; ?></b></span>
									<span class="block subtext">หมวดหมู่: <?php print $data[$i]['CAF_PDT_CAT_NAME']; ?></span>
									<span class="block subtext">ราคา: <?php  printf('%.2f', $data[$i]['CAF_PDT_PRICE']); ?></span>							
								</td>
								<td>
									<span class="block">เพิ่มเมื่อ: <?php print $data[$i]['CAF_PDT_CDATE']; ?></span>
									<span class="block">ปรับปรุง: <?php print $data[$i]['CAF_PDT_UDATE']; ?></span>
								</td>
								<td>
									<span class="icon-edit btn-hover btn-product-edit tooltips" data-toggle="tooltip" title="แก้ไข"><input type="hidden" value="<?php print $data[$i]['CAF_PDT_CODE']; ?>" name="id" /></span>
									<span class="icon-remove btn-hover btn-product-remove-item tooltips" data-toggle="tooltip" title="ลบ"><input type="hidden" value="<?php print $data[$i]['CAF_PDT_CODE']; ?>" name="id" /></span>
								</td>
							</tr>
					<?php endfor; ?> 
				<?php endif; ?>
			</tbody>
		</table>	
	</div>	
</div>
<div class="pagination">
	<?php if ($max_count > 0){?>	
		<ul>
		    <li><a href="<?php print base_url() . $cafe_name . '/backend/product?p=1';
		    					if (!empty($current_category))
		    						print '&c=' . $current_category; ?>">First</a></li>    
		    <?php for ($i=0; $i<$max_count; $i++) {?>
		      	<li><a href="<?php print base_url() . $cafe_name . '/backend/product?p=' . ($i+1); 
		      						if (!empty($current_category))
		    							print '&c=' . $current_category; ?>"><?php print $i+1; ?></a></li>
		    <?php }?>
		    <li><a href="<?php print base_url() . $cafe_name . '/backend/product?p=' . $max_count;  
		    					if (!empty($current_category))
		    						print '&c=' . $current_category; ?>">Last</a></li>
		</ul>
	<?php } ?>
</div>

<script type="text/javascript">	
	function validateName(el){
	    var name = el.val();
	    var retValue = {};
	 
	    if (name == "") {
	        retValue.status = false;
	        retValue.msg = 'โปรดระบุชื่อสินค้า';
	    }else
	        retValue.status = true;	 
	    return retValue;
	}
	function validatePrice(el){
		var name = el.val();
		var retValue = {};
		
		if (name == ""){
			retValue.status = false;
			retValue.msg = 'โปรดระบุราคาขาย';
		} else if (isNaN(name) || name <= 0){
			retValue.status = false;
			retValue.msg = 'ราคาควรเป็นตัวเลขเท่านั้นและไม่ติดลบ';
		} else
			retValue.status = true;
		return retValue;
	}
	function validateDiscount(el){
		var name = el.val();
		var retValue = {};	
		
		if ((isNaN(name) || name <= 0) && name !== ''){
			retValue.status = false;
			retValue.msg = 'ราคาควรเป็นตัวเลขเท่านั้นและไม่ติดลบ';
		} else if (($('input[name=cpp]').val() - name) <= 0){
			retValue.status = false;
			retValue.msg = 'ราคาส่วนลดไม่ควรมากกว่าราคาขาย';
		} else
			retValue.status = true;
		return retValue;
	}
	function create_product_modal(url_action, id){
		var html = '<div class="wizard" id="wizard-product">';
		
		if (id !== null)
			html += '<input type="hidden" value="' + id + '" />';
		
		html += '<h1>เพิ่มสินค้า</h1>';
		html += '<div class="wizard-card" data-cardname="name">';
		html += '	<h3>ชื่อสินค้าและหมวดหมู่</h3>';
		html += '	<div class="wizard-input-section">';
		html += '		<p>ระบุชื่อสินค้า</p>';
		html += '		<div class="control-group">';
		html += '			<input name="cpn" type="text" data-validate="validateName" />';
		html += '		</div>';
		html += '	</div>';		
		html += '	<div class="wizard-input-section">';
		html += '		<p>เลือกหมวดหมู่</p>';
		html += '		<div class="control-group">';	
		html += '			<select id="cpcat" name="cpcat"></select>';
		html += '		</div>';
		html += '	</div>';	
		html += '</div>';		
		html += '<div class="wizard-card" data-cardname="price">';
		html += '	<h3>กำหนดราคา</h3>';
		html += '	<div class="wizard-input-section">';
		html += '		<p>ราคาขาย</p>';
		html += '		<div class="control-group">';
		html += '			<input name="cpp" type="text" data-validate="validatePrice" />';
		html += '		</div>';					
		html += '	</div>';
		html += '	<div class="wizard-input-section">';
		html += '		<p>ส่วนลด (คิดเป็นบาท)</p>';
		html += '		<div class="control-group">';
		html += '			<input name="cpdc" type="text" data-validate="validateDiscount" />';
		html += '		</div>';					
		html += '	</div>';
		html += '</div>';
		html += '<div class="wizard-card" data-cardname="description">';
		html += '	<h3>รายละเอียดสินค้า</h3>';
		html += '	<div class="wizard-input-section">';
		html += '		<p>ระบุรายละเอียดสินค้า</p>';
		html += '		<textarea name="cpdesc" rows="5" cols="25"></textarea>';				
		html += '	</div>';
		html += '</div>';
		html += '<div class="wizard-card" data-cardname="image">';
		html += '	<h3>รูปภาพสินค้า</h3>';
		html += '	<div class="wizard-input-section">';
		html += '		<p></p>';					
		html += '		<div class="fileupload fileupload-new" data-provides="fileupload">';
		html += '			<span class="btn btn-file"><span class="fileupload-new">Select file</span><span class="fileupload-exists">Change</span><input type="file" name="cpimg[]" multiple="multiple" /></span>';
		html += '			<span class="fileupload-preview"></span>';
		html += '			<a href="#" class="close fileupload-exists" data-dismiss="fileupload" style="float: none">×</a>';
		html += '		</div>';
		html += '	</div>';
		html += '</div>';			
		html += '<div class="wizard-error">';
		html += '	<div class="alert alert-error"></div>';
		html += '	<a class="btn btn-primary btn-wizard-finish">กลับ</a>';
		html += '</div>';
		html += '<div class="wizard-failure">';
		html += '	<div class="alert alert-error"></div>';
		html += '	<a class="btn btn-primary btn-wizard-finish">กลับ</a>';
		html += '</div>';
		html += '<div class="wizard-success">';
		html += '	<div class="alert alert-success"></div>';						
		html += '	<a class="btn btn-primary btn-wizard-finish">เสร็จสิ้น</a>';				
		html += '</div>';
		html += '</div>';
		$('body').append(html);
		
		$.post('<?php print base_url() . $cafe_name ?>/ajax_get_category_list', function(output){
			for (var i=0; i<output.length; i++){
				$('select#cpcat').append('<option value="' + output[i].id + '">' + output[i].name + '</option>');				
			}
		}, 'json');		
		
		$.fn.wizard.logging = false;
		var wizard = $("#wizard-product").wizard({ submitUrl : url_action });
		
		wizard.show();		
		wizard.on("submit", function(wizard) {
			
			/*setTimeout(function() {
				wizard.trigger("success");
				wizard.hideButtons();
				wizard._submitting = false;
				wizard.showSubmitCard("success");
				wizard._updateProgressBar(0);
			}, 2000);*/
			$.ajax({
		        type: "POST",
		        url: wizard.args.submitUrl,
		        data: wizard.serialize(),
		        
		        success: function(output) {		            
		            output = JSON.parse(output);
					if (output.result){						
						$('#wizard-product .wizard-success').find('.alert').html(output.message);
						alert(output.message);
						wizard.submitSuccess();							
					} else {						
						$('#wizard-product .wizard-error').find('.alert').html(output.message);
						$('#wizard-product .wizard-failure').find('.alert').html(output.message);
						alert(output.message);
						wizard.submitSuccess();
					}
					wizard.hideButtons();
		            wizard.updateProgressBar(0);
					//setTimeout(function(){ window.location.reload() }, 1000);					
		        },
		        error: function() {
		            wizard.submitFailure();
		            wizard.hideButtons();
		        },
		    });
		});		
		wizard.on("reset", function(wizard) {
			wizard.setSubtitle("");
			wizard.remove();
		});	
		wizard.el.find(".btn-wizard-finish").click(function() {
			wizard.reset().close();
			$('#wizard-product').remove();
			//window.location.reload();
		});
		wizard.el.find('.wizard-close').click(function(){
			$('#wizard-product').remove();
		});
	}
	$(document).ready(function(){
		var base_url = '<?php print base_url(); ?>';       
		$('.tooltips').tooltip();	

        $('#btn-product-add').click(function(){
            create_product_modal('<?php print base_url() . $cafe_name; ?>/backend/product/ajax_add');
		});

		$('.btn-product-edit').click(function(){
			var id = $(this).find('input[name="id"]').val();
			create_product_modal('<?php print base_url() . $cafe_name; ?>/backend/product/ajax_edit', id);

			var modal = $('#modal-product');
			$.post('<?php print base_url() . $cafe_name . '/backend/product/ajax_load_previous'; ?>', { id : id}, function(output){
				modal.find('#cpn').val(output.cpn);
				modal.find('#cpp').val(output.cpp);
				modal.find('#cpdc').val(output.cpdc);
				modal.find('#cpdesc').val(output.cpdesc);
				modal.find('#cpcat').val(output.cccat);

				modal.find('.fileupload-preview').append('<img class="upload-preview" src="' + output.cpimg + '">');				
			},'json');
		});

        $('.btn-product-remove-item').on('click', function(e){	
			e.preventDefault();

        	if (confirm('ยืนยันการลบข้อมูล')){
				var id = $(this).find('input[name="id"]').val();
				var me = $(this).parents('tr');
				$.post('<?php print base_url() . $cafe_name; ?>/backend/product/ajax_remove_item', { id : id }, function(output){
					if (output.result){
						me.fadeOut(1000);
					} else {
						var html = '<div class="alert alert-error">';
						html += '<button type="button" class="close" data-dismiss="alert">&times;</button>';
						html += output.message + '</div>';
						$('.panel-message').html(html);

						autoclosealert('.alert', 2000);
					}
				}, 'json');
			}
		});
        $('#btn-product-remove-select').click(function(e){	
			e.preventDefault();

			var pl = new Array();
			var pi = new Array();
        	$('table#table-product > tbody > tr').each(function(){
            	var item = $(this).find('#chk-p');
            	if (item.is(':checked')) {
                	pl.push(item.val());
                	pi.push($(this));
            	}
        	});

        	if (pl.length > 0){
        		if (confirm('คุณต้องการลบสินค้าที่เลือกใช่หรือไม่?')){            
	    			$.post('<?php print base_url() . $cafe_name; ?>/backend/product/ajax_remove_select', { pl : pl }, function(output){
	    				if (output.result){
	    					for (i=0; i<pi.length; i++)
								pi[i].fadeOut(500);
	    				}
	    			}, 'json');
	        	}
        	}

		});
		$('#btn-select-all').click(function(){
			if ($('table#table-product tr').length > 0 ){
				var me = $(this);

				if (me.val() == '1'){
	        		me.attr('value', '0');	        		 
	        		me.removeClass('active'); 
	        		me.find('i').removeClass('icon-remove');
	        		me.find('i').addClass('icon-ok');          	
				}else{
	            	me.attr('value', '1');	            	
	            	me.addClass('active');
	            	me.find('i').removeClass('icon-ok');
	            	me.find('i').addClass('icon-remove');
				}
				
				$('table#table-product > tbody > tr').each(function(){
					if (me.val() == '1')
						$(this).children('td:eq(0)').find('#chk-p').prop('checked', true);					
					else
						$(this).children('td:eq(0)').find('#chk-p').prop('checked', false);				        		
	        	});
			}
		});       
	});
</script>